<template>
  <div>
    <el-dialog :visible.sync="channelShow" :title="'货道设置'" width="940px" @close="closeFn">
      <el-row class="channel-header">
        <el-col :span="21">
          <span>货道行数:{{ vmInfo?.vmRow }} </span>
          <span>货道列数: {{ vmInfo?.vmCol }}</span>
          <span>货道容量（个）:{{ vmInfo?.vmCol }} </span>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" size="medium" @click="recommendFn">智能排货</el-button>
        </el-col>
      </el-row>
      <div class="MyScroll">
        <button v-show="isShowBtn" class="btn leftBtn" :disabled="isPreDisabled" @click="scrollPrevious">
          <i class="el-icon-xiangzuojiantou" />
        </button>
        <button v-show="isShowBtn" class="btn rightBtn" :disabled="isNextDisabled" @click="scrollNext">
          <i class="el-icon-xiangyoujiantou" />
        </button>
        <div ref="scrollContainer" class="scrollBox">
          <el-scrollbar style="height: 400px;width: 1680px">
            <div v-for="(row,i) in data" :key="i" style="display: flex">
              <div v-for="(col,j) in row" :key="j" class="skuBox">
                <div class="skubody">
                  <div class="skuHead">
                    <span class="code">{{ col?.channelCode }}</span>
                    <img v-if="col.sku?.skuImage&&!col.sku?.skuImage.includes('lkd2-java.itheima.net')" :src="col.sku?.skuImage" alt="图片丢失">
                    <img v-else-if="col.sku===null" src="" alt="">
                    <img v-else src="@/assets/imgs/imgAlt.png" alt="">
                    <span>{{ col.sku?.skuName||'暂无商品' }}</span>
                  </div>
                  <div class="skuFoot">
                    <el-button type="text" class="blueBtn1" @click="addSkuFn(i,j)">添加</el-button>
                    <el-button type="text" class="redBtn1" style="margin-right: 0" :disabled="!col.sku?.skuName" @click="deleteSkuFn(i,j)">删除</el-button>
                  </div>
                </div>
              </div>
              <br>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="centerBox">
        <el-button type="primary1" size="medium" @click="updateChannelFn">确认</el-button>
      </div>
    </el-dialog>
    <!--    选择商品-->
    <el-dialog :visible.sync="changeSkuShow" :title="'选择商品'" width="960px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="商品名称:">
          <el-input v-model.trim="SkuParams.skuName" placeholder="请输入" clearable size="medium" @input="searchFn" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="medium" @click="searchFn">查询</el-button>
        </el-form-item>
      </el-form>
      <div v-if="isShowSkuList" class="MyScroll">
        <button v-show="isShowSkuBtn" class="btn leftBtn" :disabled="isPreSkuDisabled" @click="prevSkuPageFn">
          <i class="el-icon-xiangzuojiantou" />
        </button>
        <button v-show="isShowSkuBtn" class="btn rightBtn" :disabled="isNextSkuDisabled" @click="nextSkuPageFn">
          <i class="el-icon-xiangyoujiantou" />
        </button>
        <div class="scrollBox" style="height: 340px;display: flex">
          <div v-for="(row,i) in skuList" :key="i" style="width:840px;flex-shrink: 0;display: flex;flex-wrap: wrap">
            <div v-for="(col,j) in row" :key="j" class="skuBox" style="flex-shrink: 0;height: 160px">
              <div class="skubody">
                <div class="skuHead" style="cursor: pointer" @click="checkSku(i,j)">
                  <div v-show="col.ischeck" class="ischeck">
                    <img alt="" width="36px" src="">
                  </div>
                  <img v-if="col?.skuImage&&!col?.skuImage.includes('lkd2-java.itheima.net')" :src="col?.skuImage" alt="图片丢失">
                  <img v-else src="@/assets/imgs/imgAlt.png" alt="">
                  <span>{{ col?.skuName||'暂无商品' }}</span>
                </div>
              </div>
            </div>
            <br>
          </div>
        </div>
      </div>
      <div class="centerBox">
        <el-button type="primary1" size="medium" @click="submitAddSkuFn">确定</el-button>
      </div>
    </el-dialog>
    <!--智能排货-->
    <el-dialog :visible.sync="recommendShow" :title="'货道设置'" width="960px">
      <el-row class="channel-header" style="margin-bottom: 20px;padding-left: 20px">
        该区域属于{{ queryObj?.node?.businessType?.name }}商圈适合销售以下商品
      </el-row>
      <div class="recommendBox">
        <div v-for="item in recommendList" :key="item.skuId" class="skuItem">
          <div class="skuHead">
            <img v-if="item.image&&!item.image.includes('itheima')" :src="item.image" alt="">
            <img v-else src="@/assets/imgs/imgAlt.png" alt="图片丢失">
            <span>{{ item.skuName }}</span>
          </div>
        </div>
      </div>
      <div class="centerBox">
        <el-button type="primary1" size="medium" @click="recommendConfirmFn">采纳建议</el-button>
      </div>
    </el-dialog>

  </div></template>

<script>
import to from 'await-to-js'
import { getChannelListAPI, getRecommendAPI, getSkuListAPI, getVmtypeAPI, updateChannelAPI } from '@/api/vm'

export default {
  name: 'Channel',
  props: {
    queryObj: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 整体数据
      data: [],
      vmInfo: {},
      isShowSkuBtn: true,
      // 滚动条距离左侧的距离
      scrollLeft: 0,
      // 滚动条容器的宽度
      scrollContainerWidth: 840,
      // 是否禁用向前滚动按钮
      isPreDisabled: false,
      isPreSkuDisabled: true,
      // 是否禁用向后滚动按钮
      isNextDisabled: false,
      isNextSkuDisabled: false,
      // 是否显示滚动按钮
      isShowBtn: false,
      // 是否显示弹窗
      channelShow: true,
      recommendList: [],
      recommendShow: false,
      //   选择商品
      changeSkuShow: false,
      // 商品搜索参数
      SkuParams: {
        pageIndex: 1,
        pageSize: 10,
        skuName: ''
      },
      skuList: [],
      skutotalPage: 0,
      checkedSku: {},
      isShowSkuList: true,
      checkSkuBoxIndex: []
    }
  },
  watch: {
    vmInfo: {
      handler(val) {
        if (Object.keys(val).length && val.vmCol <= 5) {
          this.isShowBtn = false
        } else {
          this.isShowBtn = true
        }
      }
    },
    scrollLeft: {
      handler(val) {
        this.isPreDisabled = val === 0
        this.isNextDisabled = val === this.scrollContainerWidth
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.scrollContainerWidth = this.$refs.scrollContainer.offsetWidth
      this.scrollLeft = this.$refs.scrollContainer.scrollLeft
    })
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      const [err, SkuRes] = await to(getChannelListAPI(this.queryObj.innerCode))
      const [err1, vmRes] = await to(getVmtypeAPI(this.queryObj.vmType))
      if (err === null && err1 === null) {
        this.vmInfo = vmRes
        if (SkuRes?.length === 0) {
          this.$message.warning('此售货机暂无货道')
          this.channelShow = false
        }
      }
      const result = [] // 用于存储二维数组的结果
      let subArray = [] // 用于存储每个子数组的一维数组

      for (let i = 0; i < SkuRes.length; i++) {
        subArray.push(SkuRes[i])
        if (subArray.length === vmRes.vmCol) {
          result.push(subArray)
          subArray = []
        }
      }
      // 如果最后一组子数组的长度不足，也将其添加到结果中
      if (subArray.length > 0) {
        result.push(subArray)
      }
      this.data = result
    },
    // 向前滚动
    scrollPrevious() {
      const scrollContainer = this.$refs.scrollContainer
      scrollContainer.scrollLeft -= scrollContainer.offsetWidth // 向前滚动一页的宽度
      this.scrollLeft -= this.scrollContainerWidth
    },
    // 向后滚动
    scrollNext() {
      const scrollContainer = this.$refs.scrollContainer
      scrollContainer.scrollLeft += scrollContainer.offsetWidth // 向后滚动一页的宽度
      this.scrollLeft += this.scrollContainerWidth
    },
    // 下一页商品列表
    async nextSkuPageFn() {
      if (this.SkuParams.pageIndex === this.skutotalPage - 1) {
        this.isNextSkuDisabled = true
      }
      this.isPreSkuDisabled = false
      this.SkuParams.pageIndex++
      this.getSkuListFn()
    },
    // 上一页商品列表
    async prevSkuPageFn() {
      if (this.SkuParams.pageIndex === 2) {
        this.isPreSkuDisabled = true
      }
      this.isNextSkuDisabled = false
      this.SkuParams.pageIndex--
      this.getSkuListFn()
    },
    //   智能排货
    async recommendFn() {
      const [err, res] = await to(getRecommendAPI(this.queryObj.businessId))
      if (err === null && res.length) {
        this.recommendList = res
        this.recommendShow = true
      } else if (!res.length) {
        this.$message.warning('此售货机暂无智能排货')
      } else {
        this.$message.error(err.response.data)
      }
    },
    //   采纳建议
    async  recommendConfirmFn() {
      const res = await getChannelListAPI(this.queryObj.innerCode)
      this.recommendList.forEach((item, i) => {
        if (res[i]) {
          res[i].sku = {
            skuId: item.skuId,
            skuName: item.skuName,
            skuImage: item.image
          }
        }
      })
      const result = [] // 用于存储二维数组的结果
      let subArray = [] // 用于存储每个子数组的一维数组
      for (let i = 0; i < res.length; i++) {
        subArray.push(res[i])
        if (subArray.length === this.vmInfo.vmCol) {
          result.push(subArray)
          subArray = []
        }
      }
      // 如果最后一组子数组的长度不足，也将其添加到结果中
      if (subArray.length > 0) {
        result.push(subArray)
      }
      this.data = result
      this.recommendShow = false
    },
    //   删除
    deleteSkuFn(i, j) {
      this.data[i][j].sku = null
    },
    async searchFn() {
      this.SkuParams.pageIndex = 1
      this.getSkuListFn()
    },
    async getSkuListFn() {
      const res = await getSkuListAPI(this.SkuParams)
      res.currentPageRecords.forEach(item => {
        item.ischeck = false
      })
      this.isShowSkuList = !!res.currentPageRecords.length
      this.skuList = [[...res.currentPageRecords]]
      this.skutotalPage = res.totalPage
      if (+res.totalPage === 1) {
        this.isShowSkuBtn = false
      } else {
        this.isShowSkuBtn = true
      }
    },
    //   添加
    addSkuFn(i, j) {
      this.getSkuListFn()
      this.changeSkuShow = true
      this.checkSkuBoxIndex = [i, j]
    },
    // 选择了商品
    async checkSku(i, j) {
      this.checkedSku.ischeck = false
      this.$set(this.skuList[i][j], 'ischeck', !this.skuList[i][j].ischeck)
      this.checkedSku = this.skuList[i][j]
    },
    // 确认添加
    async submitAddSkuFn() {
      const [i, j] = this.checkSkuBoxIndex
      if (!this.data[i][j]) {
        return this.$message.warning('请选择商品')
      }
      this.$set(this.data[i][j], 'sku', {
        skuId: this.checkedSku.skuId,
        skuName: this.checkedSku.skuName,
        skuImage: this.checkedSku.skuImage
      })
      this.changeSkuShow = false
    },
    // 保存提交
    async updateChannelFn() {
      const list = []
      this.data.forEach(item => {
        item.forEach(item1 => {
          if (item1.sku !== null) {
            list.push({
              skuId: item1.sku.skuId,
              channelCode: item1.channelCode
            })
          }
        })
      })

      const [err] = await to(updateChannelAPI({
        innerCode: this.queryObj.innerCode,
        channelList: list
      }))
      if (err === null) {
        this.channelShow = false
      } else {
        this.$message.error(err.response.data)
        this.channelShow = false
      }
    },
    closeFn() {
      this.channelShow = false
      this.$emit('closeChannel')
    }
  }
}
</script>

<style scoped lang="scss">
.channel-header{
  height: 56px;
  line-height: 56px;
  background-color: #f3f6fb;
  span{
    margin: 0 25px;
  }
}
  .MyScroll{

    margin: 20px 0;
    position: relative;
    padding: 0 30px;
    width: 900px;
    .ischeck{
      position: absolute;
      top: 0;
      left: 0;
      >img{
        width: 36px!important;
        height: 36px!important;
      }
    }
    .btn{
      margin: 0;
      padding: 0;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      background-color: transparent;
      border: none;
      width: 30px;
      //background-color: pink;
      cursor: pointer;
      z-index: 9999;
      font-size: 30px;
      &:disabled{
        cursor: not-allowed
    }
    }
    .leftBtn{
      left: 0;
    }
    .rightBtn{
      right: 0;
    }
    .scrollBox{
      //overflow: scroll;
      overflow: hidden;
      height: 400px;
      width: 840px;
      box-sizing: border-box;
      scroll-behavior: smooth;

    }
    .skuBox{
      width: 150px;
      height: 180px;
      margin: 0 9px 20px;
      box-sizing: border-box;
      color: #fff;
      text-align: center;
      flex-shrink: 0;
      .skuHead{
        position: relative;
        color: #333;
        .code{
          position: absolute;
          top: 10px;
          left: 0;
          width: 43px;
          height: 23px;
          line-height: 23px;
          background: #829bed;
          border-radius: 0 10px 10px 0;
          font-size: 12px;
          color: #fff;
          text-align: center;
          letter-spacing:1px;
          z-index: 1;
        }
        display: flex;
        height: 140px;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #f6f7fb;
        img{
          width: 85px;
          height: 85px;
          margin-bottom: 10px;
        }
      }
      .skubody{
        position: relative;
        border-radius: 3px;
        overflow: hidden;
        box-shadow: 0 3px 5px rgba(60, 56, 56, 0.1);

        .skuFoot{
          height: 40px;
          line-height: 40px;
          background-color: #fff;
          text-align: center;
        }
      }
    }
  }
.recommendBox{
  .skuItem{
    width: 20%;
    padding: 0 10px;
    display: inline-block;
    box-sizing: border-box;
    margin-bottom: 20px;
    .skuHead{
      position: relative;
      .code{
        position: absolute;
        top: 10px;
        left: 0;
        width: 43px;
        height: 23px;
        line-height: 23px;
        background: #829bed;
        border-radius: 0 10px 10px 0;
        font-size: 12px;
        color: #fff;
        text-align: center;
        letter-spacing:1px;
        z-index: 1;
      }
      display: flex;
      height: 140px;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: #f6f7fb;
      img{
        width: 85px;
        height: 85px;
        margin-bottom: 10px;
      }
    }
    .skubody{
      position: relative;
      border-radius: 3px;
      overflow: hidden;
      box-shadow: 0 3px 5px rgba(60, 56, 56, 0.1);

      .skuFoot{
        height: 40px;
        line-height: 40px;
        background-color: #fff;
        text-align: center;
      }
    }
    .ischeck{
      position: absolute;
      top: 0;
      left: 0;
      img{
        width: 36px;
        height: 36px;
      }
    }
  }
}
</style>
